package com.gxuwu.admin.service.impl;

import com.gxuwu.admin.entity.MyUser;
import com.gxuwu.admin.entity.Permission;
import com.gxuwu.admin.entity.SecurityUser;
import com.gxuwu.admin.service.MyUserService;
import com.gxuwu.admin.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {



    @Autowired
    private MyUserService userService;

    @Autowired
    private PermissionService permissionService;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SecurityUser securityUser = new SecurityUser();
        MyUser loginUser = userService.login(username);
        if(loginUser==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        List<String> permissionValueList=new ArrayList<>();

        List<Permission>  allPermission = permissionService.getAllPermission();
        for (Permission permission:allPermission){
            String authName=permission.getPermissionValue();
            if (authName!=null ){
                permissionValueList.add(authName);
            }
        }

//        securityUser.setUsername(username);
//        securityUser.setPassword(loginUser.getPassword());
        securityUser.setUserInfo(loginUser);
        securityUser.setPermissionValueList(permissionValueList);


//        User user = new User(username, loginUser.getPassword(), permissionValueList);


        return securityUser;
    }
}
